<template>
  <div class="wrape-content">
    <div class="top">
      <img src="../../assets/user-image/location.png" alt="位置">
      <span>您当前所在的位置：短信服务/分组管理</span>
    </div>
    <div class="content">
      <div class="form">
        <el-form :model="ruleForm" label-width="80px" class="ruleForm">
          <el-form-item label="分组类别">
            <el-select
              v-model="ruleForm.className"
              placeholder="请选择分组类别"
              @change="changeSelect_class"
            >
              <el-option
                v-for="(item,index) in options"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <section class="oprtionbtn">
            <el-button type="primary" class="feicuilu" icon="el-icon-plus" @click="addClass ">新增分组</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteClass">删除分组</el-button>
            <el-button type="primary" icon="el-icon-edit" @click="edClassName">编辑分组</el-button>
          </section>
        </el-form>
      </div>
      <div class="Table">
        <el-table
          style="width:98%;margin:0 auto"
          show-overflow-tooltip
          :height="height"
          border
          :data="tableData"
        >
          <el-table-column
            v-for="(item,index) in tableHeaderData"
            show-overflow-tooltip
            :key="index"
            :prop="item.prop"
            :label="item.label"
            align="center"
          ></el-table-column>
          <el-table-column label="操作" align="center" width="120">
            <template slot-scope="scope">
              <div class="actionbtn" style="background:#24B3B3">
                <img @click="upDataUser(scope.row)" src="../../assets/edit.png" title="修改">
              </div>
              <div class="actionbtn" style="background:#F56262">
                <img @click="handDelete(scope.row)" src="../../assets/delete_right.png" title="删除">
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        @current-change="handleCurrentChange_class"
        @size-change="handleSizeChange_class"
        :current-page="current_page_class"
        :page-sizes="[15,50,100]"
        :page-size="pageSize_class"
        layout="total, sizes, prev, pager, next, jumper"
        :total="class_total"
      ></el-pagination>
    </div>
    <el-dialog class="Notic" :visible.sync="AddDialog" :title="edititle" width="60%">
      <span style="font-size:17px;color:#041f41">
        <b>基本信息:</b>
      </span>
      <div class="from">
        <el-form
          :model="NoticruleForm"
          :rules="rules"
          ref="NoticruleForm"
          label-width="140px"
          class="NoticruleForm"
        >
          <el-form-item label="分组名称" prop="classname">
            <el-input placeholder="请输入分组名称" clearable v-model="NoticruleForm.classname"></el-input>
          </el-form-item>
          <el-form-item
            label="添加系统用户至分组"
            prop="serchuser"
            class="adduser_class"
            v-if="edititle== '编辑分组'"
          >
            <el-input
              size="medium"
              placeholder="请输入用户姓名或者手机号"
              suffix-icon="el-icon-serch"
              v-model="NoticruleForm.userName"
              :disabled="nouserSystem"
            ></el-input>
            <el-button type="primary" icon="el-icon-search" @click="SerchUser">搜索</el-button>
            <el-button
              style="width:auto"
              type="primary"
              icon="el-icon-plus"
              @click="nouserSystem = !nouserSystem"
            >添加非系统用户</el-button>
            <!-- <span class="info">系统中不存在此用户，请填写下列信息，新增用户至此分组中</span> -->
          </el-form-item>
        </el-form>
        <div class="moveUser" v-if="edititle == '编辑分组' ">
          <div v-if="!nouserSystem" style="text-align:center">
            <el-table
              row-key="id"
              ref="multipleTable"
              :data="userData"
              border
              height="300"
              @selection-change="handleSelectionChange"
            >
              <el-table-column align="center" type="selection" width="55" :reserve-selection="true"></el-table-column>
              <el-table-column
                v-for="(item,index) in userTableHeader"
                show-overflow-tooltip
                :key="index"
                :prop="item.prop"
                :label="item.label"
                align="center"
                :width="item.width"
              ></el-table-column>
            </el-table>
            <el-pagination
              style="width: 75%;
    margin: 0 auto;"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
              :current-page="current_page"
              :page-sizes="[15,50,100]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next"
              :total="total"
            ></el-pagination>
            <span style="font-size:12px;color:red">已选择{{length}}个用户</span>
          </div>
          <el-form
            :model="NoticruleForm"
            :rules="editrules"
            ref="NoticruleForm"
            label-width="140px"
            class="NoticruleForm"
            v-if="nouserSystem"
          >
            <el-form-item label="姓名" prop="name">
              <el-input placeholder="请输入新增用户姓名" clearable v-model="NoticruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="telphone">
              <el-input placeholder="请输入电话号码" clearable v-model.number="NoticruleForm.telphone"></el-input>
            </el-form-item>
            <el-form-item label="行政级别" prop="level">
              <el-select
                v-model="NoticruleForm.level"
                placeholder="请选择"
                @change="changeSelectlevel"
              >
                <el-option value="省" label="省"></el-option>
                <el-option value="市" label="市"></el-option>
                <el-option value="县" label="县"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="行政区域" prop="area_code">
              <el-cascader v-model="NoticruleForm.area_code" placeholder="请选择行政区域" :options="citys"></el-cascader>
            </el-form-item>
            <el-form-item label="单位类型" prop="unit_type">
              <el-input v-model="NoticruleForm.unit_type" placeholder="例：交通厅/交通局/公路局"></el-input>
            </el-form-item>
            <el-form-item label="职位" prop="position">
              <el-input v-model="NoticruleForm.position" placeholder="例：局长"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="resetForm('NoticruleForm')">重置</el-button>
        <el-button type="primary" class="feicuilu" @click="submitForm('NoticruleForm')">确定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户模块弹窗 -->
    <el-dialog class="Notic" :visible.sync="userDialog" title="修改用户信息" width="60%">
      <span style="font-size:17px;color:#041f41">
        <b>分组信息:</b>
      </span>
      <div class="from">
        <el-form :model="NoticruleForm" label-width="140px" class="NoticruleForm">
          <el-form-item label="用户所在分组">
            <el-select
              v-model="ruleForm.className"
              placeholder="请选择分组类别"
              @change="changeSelect_user"
            >
              <el-option
                v-for="(item,index) in options"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" class="feicuilu" @click="updatedClassUser">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import publicData from "../../publicJS/publicData";
import { callbackify } from "util";
export default {
  data() {
    var Rgecellphone = (rules, value, callback) => {
      let reg = /^1(3|4|5|7|8|6|9)\d{9}$/;
      if (value == "" || value == undefined) {
        callback(new Error("请输入手机号码！"));
      }
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error("您输入的号码有误，请输入正确号码！"));
      }
    };
    return {
      city: JSON.parse(JSON.stringify(publicData.city)),
      citys: [],
      length: 0,
      classnameId: 0, // 查询分组的ID
      classnameid_user: 0,
      classname: "", // 编辑的分组名字,
      current_page_class: 1, //
      pageSize_class: 15,
      class_total: 0,
      total: 0,
      rowID: 0, //修改用户时 需要传递的id,
      current_page: 1,
      pageSize: 15,
      userData: [], // 添加用户至分组时查询用户的数据
      nouserSystem: false, // 非系统用户显示表单添加
      ruleForm: {
        className: ""
      },
      NoticruleForm: {
        classname: "",
        level: "",
        unit_type: "",
        area_code: ""
      },
      rules: {
        classname: [
          { required: true, message: "请输入分组名称", trigger: "blur" }
        ]
      },
      edititle: "新增分组", // 还是查看
      editrules: {
        name: [{ required: true, message: "请输入分组名称", trigger: "blur" }],
        telphone: [
          { required: true, validator: Rgecellphone, trigger: "blur" }
        ],
        level: [
          { required: true, message: "请选择行政等级", trigger: "change" }
        ],
        area_code: [
          { required: true, message: "请选择行政区域", trigger: "change" }
        ],
        unit_type: [
          { required: true, message: "请输入单位类型", trigger: "blur" }
        ]
      },
      userid: [],
      saveUserid: [],
      AddDialog: false,
      userDialog: false,
      options: [
        // 分组选项
      ],
      tableData: [],
      height: [],
      userTableHeader: [
        {
          prop: "dataindex",
          label: "序号",
          width: 60
        },
        {
          prop: "name",
          label: "姓名",
          width: 90
        },
        {
          prop: "cellphone",
          label: "联系方式"
        }
      ],
      tableHeaderData: [
        {
          prop: "dataindex",
          label: "序号",
          width: "60"
        },
        {
          prop: "user_name",
          label: "姓名"
        },
        {
          prop: "mobile",
          label: "联系方式"
        },
        {
          prop: "level",
          label: "行政等级"
        },
        {
          prop: "area_name",
          label: "行政区域"
        },
        {
          prop: "unit_type",
          label: "单位类型"
        },
        {
          prop: "position",
          label: "职位"
        }
      ]
    };
  },
  updated() {
    console.log(this.NoticruleForm);
    try {
    } catch (error) {}
  },
  methods: {
    handDelete(row) {
      // 删除此人在这个分组的信息
      this.$w.confirm(`是否删除当前组内的${row.user_name}用户`, () => {
        this.$ajax
          .post("/index.php/texting/Member/del", {
            id: row.id
          })
          .then(res => {
            if (res.data.code == 1) {
              this.$w.messages(1, res.data.msg);
              this.getclassNumber();
            } else {
              this.$w.messages(0, res.data.msg);
            }
          });
      });
    },
    getclassName() {
      // 获取所有分组
      this.$ajax("/index.php/texting/Group/allGroup")
        .then(res => {
          if (res.data.code > 0) {
            let options = res.data.list;
            this.options = []; // 清空分组数组
            options.forEach((item, index) => {
              let obj = {};
              obj.label = item.name;
              obj.value = item.id;
              this.options.push(obj);
            });
            this.$set(this.ruleForm, "className", this.options[0].label);
            this.$set(this.NoticruleForm, "classname", this.options[0].label);
            this.classnameId = this.options[0].value;
            // 查询到了分组信息 在获取此分组下的成员信息
            this.getclassNumber();
          } else {
            this.ruleForm.className = [];
            this.$w.messages(0, res.data.msg);
          }
        })
        .then(() => {});
    },
    getclassNumber() {
      this.$ajax
        .post("/index.php/texting/Member/allMember", {
          current_page: this.current_page_class,
          per_page: this.pageSize_class,
          group_id: this.classnameId
        })
        .then(res => {
          if (res.data.code > 0) {
            res.data.msg.data.forEach((item, index) => {
              item.dataindex = index + 1;
            });
            this.tableData = res.data.msg.data;
            this.class_total = res.data.msg.total;
          } else {
            this.tableData = []
            console.log('组成员',this.tableData)
            this.class_total = 0;
            this.$w.messages(0, res.data.msg);
          }
        });
    },
    addMessaeg() {
      //
      this.AddDialog = true;
    },
    handleCommand(item) {
      console.log(item);
    },

    submitForm(formName) {
      if (this.edititle == "编辑分组") {
        if (this.nouserSystem) {
          // 编辑分组下添加非系统用户需要表单验证
          this.$refs[formName].validate(valid => {
            if (valid) {
              console.log("验证通过");
              this.updatedClass();
              console.log(this.NoticruleForm);
            } else {
              return false;
            }
          });
        } else {
          this.updatedClass();
        }
      } else {
        this.addClassName(); // 新增一个分组
      }
    },
    resetForm(formName) {
      // 重置查询的条件

      this.$refs[formName].resetFields();
      this.NoticruleForm = {};
    },
    updatedClass() {
      // 更新组信息
      let url = "/index.php/texting/Member/save";
      let parms = {};
      if (!this.nouserSystem) {
        url = "/index.php/texting/Member/addAll";
        let id = this.saveUserid.length == 0 ? this.userid : this.saveUserid;
        console.log("传过去的数组", id);
        let ids = id.map(item => {
          return item.id;
        });
        parms = {
          ids: ids,
          group_id: this.classnameId
        };
      } else {
        parms = {
          group_id: this.classnameId,
          user_name: this.NoticruleForm.name,
          unit_type: this.NoticruleForm.unit_type,
          position: this.NoticruleForm.position,
          mobile: this.NoticruleForm.telphone,
          level: this.NoticruleForm.level
        };
        if (this.NoticruleForm.area_code) {
          parms.area_code =
            this.NoticruleForm.area_code.length >= 1
              ? this.NoticruleForm.area_code.pop()
              : this.NoticruleForm.area_code;
        }
      }
      this.$ajax.post(url, parms).then(res => {
        if (res.data.code > 0) {
          this.$w.messages(1, "修改分组信息成功");
          this.AddDialog = false;
          this.getclassNumber();
        } else {
          this.$w.messages(0, res.data.msg);
          this.AddDialog = true;
        }
      });
    },
    addClassName() {
      this.$ajax
        .post("/index.php/texting/Group/save", {
          group_name: this.NoticruleForm.classname
        })
        .then(res => {
          if (res.data.code > 0) {
            this.$w.messages(1, "新增分组成功");
            this.AddDialog = false;
            this.getclassName();
          } else {
            this.$w.messages(0, "新增分组失败");
          }
        });
    },
    addClass() {
      (this.AddDialog = true), (this.edititle = "新增分组");
      this.NoticruleForm.classname = "";
    },
    deleteClass() {
      // 删除分组\
     
      if(this.tableData.length == 0){
        this.$w.messages(0, '没有组员无法删除');
        return false 
      }
      this.$w.confirm(
        `是否删除当前组内的${this.tableData.length}个成员`,
        () => {
          this.$ajax
            .post("/index.php/texting/Group/del", {
              group_id: this.classnameId
            })
            .then(res => {
              if (res.data.code > 0) {
                this.getclassName();
              } else {
                this.$w.messages(0, res.data.msg);
              }
            });
        }
      );
    },
    edClassName() {
      // 编辑分组
      this.edititle = "编辑分组";
      this.AddDialog = true;
      this.clearSelect();
      let options = JSON.parse(JSON.stringify(this.options));
      console.log("此时的classnameid", this.classnameId);
      let classname = options.filter(item => {
        return item.value == this.classnameId;
      });
      console.log("过滤", classname);
      this.$set(this.NoticruleForm, "classname", classname[0].label);
    },

    updatedClassUser() {
      //更新用户所属分组
      console.log(
        "用户选择的分组id",
        this.classnameid_user,
        "用户id",
        this.rowID
      );
    },

    SerchUser() {
      let param = {
        per_page: this.pageSize,
        current_page: this.current_page
      };
      // 判断用户输入的是 姓名还是电话号码
      if (this.NoticruleForm.userName.match(/[\u4e00-\u9fa5]/g)) {
        param.name = this.NoticruleForm.userName;
      } else if (this.NoticruleForm.userName.match(/\d/g)) {
        param.telphone = parseInt(this.NoticruleForm.userName);
      }
      this.$ajax
        .post("/index.php/texting/Group/queryUsers", param)
        .then(res => {
          console.log(res);
          if (res.data.code == 1) {
            this.userData = res.data.msg.data.map((item, index) => {
              item.dataindex = item.id;
              return item;
            });
            this.total = res.data.msg.total;
            console.log(this.userData);
          } else {
            this.$w.messages(0, res.data.msg);
          }
        })
        .catch(err => {});
    },
    handleSizeChange(per_page) {
      this.pageSize = per_page;
      this.SerchUser();
    },

    // 判断数据是否相等

    handleSelectionChange(value) {
      //:serve- chang 会主动调用这个函数
      /*  this.userid = value.map((item, index) => {
          return item.id;
        });*/
      this.userid = value;
      let save = [];
      if (value.length >= 3) {
        for (let i = value.length - 1; i >= 1; i--) {
          for (let j = i - 1; j >= 0; j--) {
            try {
              if (value[i].id == value[j].id) {
                console.log("有重复");
                value.splice(j, 1);
              } else {
              }
            } catch (error) {
              console.log(error);
            }
          }
        }
      }

      console.log("选择用户的id", value);
      // if (this.userid.length <=1) {
      this.length = this.userid.length;
      // } else {

      // }
    },
    getRowKeys(row) {
      return row.id;
    },

    handleCurrentChange(current_page) {
      //  选择分页后的大小
      this.current_page = current_page;

      this.saveUserid = this.saveUserid.concat(this.userid);
      this.SerchUser();
      this.$nextTick(() => {
        this.userid = [];
        this.toggleSelection(this.saveUserid);
      });
    },
    clearSelect() {
      this.$refs.multipleTable.clearSelection();
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          // console.log("渲染所选的用户", row);
          this.$refs.multipleTable.toggleRowSelection(row, true);
        });
      } else {
        // this.$refs.multipleTable.clearSelection();
      }
    },
    handleCurrentChange_class(page) {
      this.current_page_class = page;
      this.getclassNumber();
    },
    handleSizeChange_class(page_size) {
      this.pageSize_class = page_size;
      this.getclassNumber();
    },
    changeSelect_class(item) {
      this.classnameId = item;
      console.log("分组ID", this.classnameId);

      this.getclassNumber();
    },

    changeSelect_user(item) {
      this.classnameid_user = item;
      console.log("用户分组ID", this.classnameid_user);
    },
    changeSelectlevel(value) {
      console.log(value);
      this.citys = JSON.parse(JSON.stringify(this.city));
      if (value == "市") {
        this.citys = this.citys[0].children.filter(res => {
          return delete res.children;
        });
      } else if (value == "县") {
        this.citys = this.citys[0].children;
      } else {
        this.citys = [{ id: 1, value: "430000", label: "湖南省" }];
      }
    },
    upDataUser(row) {
      this.classnameid_user = this.classnameId;
      this.userDialog = true;
      this.rowID = row.id;
    }
  },
  watch: {
    current_page(value) {
      this.userid = [];
      //this.saveUserid = this.saveUserid.concat(this.userid);
    },
    userid(value) {}
  },
  created() {
    this.height = window.screen.height - 225 + "px";
    this.getclassName();
  }
};
</script>

<style lang="stylus" scoped>
.wrape-content {
  flex: 1;
  background: rgb(241, 242, 247);
  padding: 0% 1.1%;
}

.content {
  background: white;
  box-shadow: 0px 3px 10px 0px rgba(0, 0, 0, 0.05);
  padding-bottom: 40px;
}

.top {
  background: white;
  font-size: 13px;
  margin-bottom: 12px;
  color: #4D4D4D;
  box-shadow: 0px 3px 10px 0px rgba(0, 0, 0, 0.05);
  line-height: 35px;
  padding-left: 5px;

  span {
    margin-left: 5px;
  }
}

.form, .ruleForm >>> {
  .el-form-item__label-wrap {
    margin-left: 15px;
  }
}

.ruleForm {
  display: flex;
  align-items: center;

  .el-form-item {
    margin-top: 9px;
    flex: 0 0 24%;
  }
}

.addbtn img, .exportbtn img, .deletebtn img {
  vertical-align: bottom !important;
}

.Table {
  margin-top: 9px;
  border-top: 1px solid #E5E5E5;
  background: rgba(255, 255, 255, 1);
  box-shadow: 0px 3px 10px 0px rgba(0, 0, 0, 0.05);
}

.Table >>> {
  .el-table {
    margin-top: 10px !important;

    th {
      background-color: rgba(235, 240, 255, 1) !important;
      padding: 8px 0;
    }
  }
}

.Table >>> {
  .el-table__body-wrapper {
    td {
      padding: 7.5px;
    }
  }
}

.actionbtn {
  display: inline-block;
  width: 23px;
  height: 23px;
  padding: 2px 1px;
  margin-left: 5px;
  border-radius: 5px;
  cursor: pointer;
}

.Notic >>>.el-dialog__header {
  background: rgb(4, 31, 65);

  .el-dialog__title {
    color: white;
  }
}

.NoticruleForm {
  display: flex;
  margin-top: 30px;
  flex-wrap: wrap;
  justify-content: flex-start;
  margin-left: 58px;

  .el-form-item {
    flex: 0 0 80%;
  }

  .el-select {
    display: block;
  }

  .el-cascader {
    display: block;
  }
}

.textarea >>> {
  .el-textarea__inner {
    height: 150px;
  }
}

.noativebtn {
  pointer-events: none;
  background: #66b1ff !important;
  border-color: #66b1ff !important;
  color: #FFF;
}

.oprtionbtn {
  margin-left: 20px;
}

.moveClass {
  width: 70%;
  margin: 0 auto;
}

.adduser_class /deep/ .el-form-item__content {
  display: flex;
  align-items: center;
  position: relative;

  button {
    margin-left: 20px;
  }

  .info {
    position: absolute;
    top: 30px;
    color: red;
  }
}

.moveUser >>> .el-table {
  width: 50%;
  margin: 0 auto;
}

.el-pagination {
  padding: 1.1%;
  display: flex;
  justify-content: center;
  background: #F5F8FF;
}
</style>